package cn.formaggie.service.impl;

import cn.formaggie.dao.PermissionDao;
import cn.formaggie.entity.model.roleandpermission.Permission;
import cn.formaggie.service.face.BackManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("backManageService")
public class BackManageServiceImpl implements BackManageService{

    @Autowired
    private PermissionDao permissionDao;


    @Override
    public Map<String, List<Permission>> getPermissionsWithTypeByRoleId(Integer roleId) {
        Map<String,List<Permission>> typeAndPermissions=new HashMap<>();
        List<Permission> permissions=permissionDao.getPermissionsByRoleId(roleId);
        List<Integer> indexs=findTypeIndex(permissions);
        if(indexs==null){
            return null;
        }
        for(int i=0;i<indexs.size();i++){
            String typeName=permissions.get(indexs.get(i)).getPermissionType().getPermissionType();
            List<Permission> permissionList=new ArrayList<>();
            int start=indexs.get(i);
            int end=indexs.get((i+1)<(indexs.size()-1)?(i+1):indexs.size()-1);
            if(i==indexs.size()-1){
                end=permissions.size();
            }
            for(int pIndex=start;pIndex<end;pIndex++){
                permissionList.add(permissions.get(pIndex));
            }
            typeAndPermissions.put(typeName,permissionList);
        }
        return typeAndPermissions;
    }


    private List<Integer> findTypeIndex(List<Permission> permissions){
        if(permissions.size()==0){
            return null;
        }
        List<Integer> indexs=new ArrayList<>();
        boolean isTypeChange=true;
        String typeName=permissions.get(0).getPermissionType().getPermissionType();
        indexs.add(0);
        for(int i=0;i<permissions.size();i++){
            String tempName=permissions.get(i).getPermissionType().getPermissionType();
            if(tempName.equals(typeName)){
                continue;
            }else{
                indexs.add(i);
                typeName=tempName;
            }
        }
        return indexs;
    }
}
